package com.concurrent.concurrentdemo.lock;

import org.junit.Test;

import java.util.concurrent.*;

public class SynchronizedDemo {

    private static int num = 0;

    public void normalPlus() {
        num++;
    }

    public synchronized void objectSyncPlus() {
        num++;
    }

    public void blockSyncObjectPlus() {
        synchronized (this) {
            num++;
        }
    }

    public void blockSyncClassPlus() {
        synchronized (SynchronizedDemo.class) {
            num++;
        }
    }

    public static synchronized void classSyncPlus() {
        num++;
    }

    public static void main(String[] args) {
        SynchronizedDemo demo = new SynchronizedDemo();
        demo.objectSyncPlus();
        demo.classSyncPlus();
    }

    /**
     * 多线程并发自增
     */
    @Test
    public void testPlus(){
        ExecutorService pool = Executors.newFixedThreadPool(10);
        SynchronizedDemo demo01 = new SynchronizedDemo();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(11);
        for (int i = 0; i < 10; i++) {
            pool.execute(() -> {
                for (int j = 0; j < 10000; j++) {
                    demo01.normalPlus();
                }
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        try {
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(num);
        pool.shutdown();
    }

}
